import re

from rest_framework import serializers

from areas.models import Area
from users.models import Address


class AreasSerializer(serializers.ModelSerializer):

    class Meta:
        model = Area

        fields = ('id', 'name')


class AddressSerializer(serializers.ModelSerializer):

    # 显示指明没有的字段
    city = serializers.StringRelatedField(read_only=True)
    province = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)


    """
    city_id:120100
    district_id:120102
    email:""
    mobile:"13844444444"
    place:"aaaaaaaa"
    province_id:120000
    receiver:"python"
    tel:""
    title:"python"
    """

    class Meta:
        model = Address
        fields = ('city_id', 'district_id',
                  'email', 'mobile', 'province',
                  'place', 'province_id',
                  'receiver', 'tel', 'title',
                  'city', 'district', 'id')

    # 验证手机号
    def validate_mobile(self, value):
        if not re.match(r'1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机格式匹配不对')
        return value

    def create(self, validated_data):

        # 获取用户对象
        user = self.context['request'].user
        validated_data['user'] = user
        address = Address.objects.create(**validated_data)

        return address
